package cn.acewill.yxd.yunxundian.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.departBean;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.NotificationsUtils;
import cn.acewill.yxd.yunxundian.utils.baiduUtils.InputUtil;

public class LoginActivity extends BaseActivity implements View.OnClickListener,TextWatcher{
    private EditText userNum,userPass;
    private String uNum,uPass;
    private SharedPreferences sp;
    NetWorkStateReceiver netWorkStateReceiver;
    private TextInputLayout userNameWrapper,passWrapper;
    private Animation shake;
    private TextView configIP;
    private String IPName,branchName;
    private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS;
    private CheckBox rememberBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatService.setOn(this, StatService.EXCEPTION_LOG);
        StatService.start(this);
        setContentView(R.layout.activity_login);
        initView();
        shake = AnimationUtils.loadAnimation(this,R.anim.edtext_shake);
        getAllPerssion();
    }

    public void initView() {
        this.passWrapper= (TextInputLayout) findViewById(R.id.passWrapper);
        this.userNameWrapper  = (TextInputLayout) findViewById(R.id.userNameWrapper);
        this.userNum = (EditText) findViewById(R.id.userNum);
        this.userPass = (EditText) findViewById(R.id.userPass);
        Button loginIn = (Button) findViewById(R.id.loginIn);
        loginIn.setOnClickListener(this);
        userNum.addTextChangedListener(this);
        this.configIP= (TextView) findViewById(R.id.configIP);
        configIP.setOnClickListener(this);
        rememberBox = (CheckBox) findViewById(R.id.rememberBox);
        rememberBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor ed=sp.edit();
                if (isChecked){
                   ed.putBoolean("rememberPass",true);
                }else{
                    ed.putBoolean("rememberPass",false);
                }
                ed.apply();
            }
        });
        InputUtil.getInstance(this).setEditTextInhibitInputSpeChat(userNum);
        InputUtil.getInstance(this).setEditTextInhibitInputSpeChat(userPass);

        //获取通知权限
        boolean isNeedRequest = NotificationsUtils.isNotificationEnabled(this);
        if (!isNeedRequest)
            Toast.makeText(this,"您禁止了通知权限，可在应用通知设置中打开",Toast.LENGTH_SHORT).show();
         setDefaultValue();
    }
    private void setDefaultValue(){
        sp=getSharedPreferences("yxdUrl",MODE_PRIVATE);
        userNum.setText(sp.getString("userNum",""));
        boolean ischeck = sp.getBoolean("rememberPass",false);
        rememberBox.setChecked(ischeck);
        if (ischeck){
            userPass.setText(sp.getString("userPass",""));
        }
    }


    //网络请求，先加载本地数据，无则输入
    protected void userLogin(){
        uNum =userNum.getText().toString().trim();
        uPass=userPass.getText().toString().trim();
        IPName=sp.getString("IpName","");
        branchName=sp.getString("branchName","");
        if (TextUtils.isEmpty(IPName)){
            if (configIP.getAnimation() != null) {
                configIP.clearAnimation();
            }
            configIP.setAnimation(shake);
            configIP.startAnimation(shake);
            return;
        }
        if (TextUtils.isEmpty(uNum)&&TextUtils.isEmpty(uPass)){
            if(userNameWrapper.getAnimation()!=null){
                userNameWrapper.clearAnimation();
            }
            if (passWrapper.getAnimation()!=null){
                passWrapper.clearAnimation();
            }
            userNameWrapper.setAnimation(shake);
            userNameWrapper.startAnimation(shake);
            passWrapper.setAnimation(shake);
            passWrapper.startAnimation(shake);
            return;
        }
        if(TextUtils.isEmpty(uNum)){
            if(userNameWrapper.getAnimation()!=null){
                userNameWrapper.clearAnimation();
            }
            userNameWrapper.setAnimation(shake);
            userNameWrapper.startAnimation(shake);
            return;
        }
        if (TextUtils.isEmpty(uPass)){
            if (passWrapper.getAnimation()!=null){
                passWrapper.clearAnimation();
            }
            passWrapper.setAnimation(shake);
            passWrapper.startAnimation(shake);
            return;
        }
        //判断pubclass的url是否为空，空就设置
        if (TextUtils.isEmpty(pubClass.Server_namehzm)){
            pubClass.seturl(this);
        }
        clearDb();
    }

    private ProgressDialog dialog;
    public void longinRequest(){
        //登录请求，成功则保存数据saveUser,然后进行页面跳转
        Map<String,String> map=new HashMap<>();
        map.put("task","loginByUserNumAndPwd");
        map.put("usernum",uNum+"");
        map.put("pwd",uPass+"");
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在登陆");
        setdefultDialog(dialog);
        dialog.show();
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            try {
                OkHttpManger.getInstance().postAsync(this,pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                    @Override
                    public void onSuccess(String result) {
                        String[] strings=result.split("\\|");
                        if(strings[0].equals("201")){
                            showAnimaDialog(LoginActivity.this,strings[1]);
                            if(strings[1].equals("用户名不存在")){
                                userNum.setAnimation(shake);
                                userNum.startAnimation(shake);
                            }else{
                                userPass.setAnimation(shake);
                                userPass.startAnimation(shake);
                            }
                        }
                        if(strings[0].equals("200")) {
                            //json转化为对象；
                            Gson gson = new Gson();
                            Type typeList = new TypeToken<ArrayList<Employee>>() {
                            }.getType();
                            ArrayList<Employee> emps = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                            try {
                       //         clearShopAndSchedule();
                                db.saveOrUpdate(emps);
                                saveUserInfo();
                                Employee emp=db.selector(Employee.class).where("usernum","=",uNum+"").findFirst();
                                int userId=emp.getID();
                                String firstName=emp.getFirstName();
                                Intent in=new Intent(LoginActivity.this, SynchronizationAtivity.class);
                                in.putExtra("userId",userId);
                                in.putExtra("userName",firstName);
                                startActivity(in);
                                finish();

                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                        if (dialog!=null&&dialog.isShowing()){
                            dialog.dismiss();
                        }
                    }
                    @Override
                    public void onFailture() {
                        if (dialog!=null&&dialog.isShowing()){
                            dialog.dismiss();
                        }
                        BaseActivity.showAnimaDialog(LoginActivity.this,"网络不是很好");
                    }
                }, map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else{
            if (dialog.isShowing()){
                dialog.dismiss();
            }
            String usernum=sp.getString("userNum","null");
            String pass=sp.getString("userPass","null");
            if (usernum.equals(uNum)&&pass.equals(uPass)){
                //可以登录，拿到用户的id
                try {
                    Employee emp=db.selector(Employee.class).where("userNum","=",usernum).findFirst();
                    Intent in=new Intent(LoginActivity.this, MainActivity.class);
                    in.putExtra("userId",emp.getID());
                    startActivity(in);
                    finish();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } if (!usernum.equals(uNum)){
                if(userNum.getAnimation()!=null){
                    userNum.clearAnimation();
                }
                userNum.setAnimation(shake);
                userNum.startAnimation(shake);
                showAnimaDialog(LoginActivity.this,"用户名不存在！");
                return;

            } if(!pass.equals(uPass)){
                if(userPass.getAnimation()!=null){
                    userPass.clearAnimation();
                }
                userPass.setAnimation(shake);
                userPass.startAnimation(shake);
                showAnimaDialog(LoginActivity.this,"密码错误！");

            }
        }
    }


    //IP保存在sharepreference中
    public void saveUserInfo(){
        SharedPreferences.Editor ed=sp.edit();
        ed.putString("userNum",uNum);
        ed.putString("userPass",uPass);
        ed.apply();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.loginIn:
                userLogin();
                break;
            case R.id.configIP:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View view = LayoutInflater.from(this).inflate(R.layout.input_network_dialog, (ViewGroup) getWindow().getDecorView(),false);
                builder.setView(view);
                final EditText companyName = (EditText) view.findViewById(R.id.companyName);
                final EditText IpPass = (EditText) view.findViewById(R.id.ipPass);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String name = companyName.getText().toString().trim();
                        String ipass = IpPass.getText().toString().trim();
                        ipDialog = new ProgressDialog(LoginActivity.this);
                        ipDialog.setMessage("正在检查IP地址");
                        setdefultDialog(ipDialog);
                        ipDialog.show();
                        checkIpAvailable(name,ipass);
                    }
                });
                builder.show();
                break;
        }
    }
    ProgressDialog ipDialog;
    public void checkIpAvailable(String name,String  pass){
        Map<String,String> map=new HashMap<>();
        map.put("task","getServerInfo");
        map.put("code",name);
        map.put("pwd",pass);
        if (NetWorkStateReceiver.whetherConnectNetWork==1) {
            try {
                OkHttpManger.getInstance().postAsync(pubClass.checkUrl, new OkHttpManger.MyCallback() {
                    @Override
                    public void onSuccess(String result) {
                        String str[] = result.split("\\|");
                        if (str[0].equals("200")) {
                            showAnimaDialog(LoginActivity.this, "配置检验成功，请登录");
                            IPName = str[3];
                            branchName = str[4];
                            //save
                            SharedPreferences.Editor ed=sp.edit();
                            ed.putString("IpName",IPName);
                            ed.putString("branchName",branchName);
                            ed.apply();
                            pubClass.seturl(LoginActivity.this);
                        } else {
                            Toast.makeText(LoginActivity.this,"该地址未配置入服务器，请联系管理员",Toast.LENGTH_SHORT).show();
                           // showAnimaDialog(LoginActivity.this, "该地址未配置入服务器，请联系管理员");
                            if (configIP.getAnimation() != null) {
                                configIP.clearAnimation();
                            }
                            configIP.setAnimation(shake);
                            configIP.startAnimation(shake);
                        }
                        if (ipDialog!=null&&ipDialog.isShowing()){
                            ipDialog.dismiss();
                        }
                    }
                    @Override
                    public void onFailture() {
                        if (ipDialog!=null&&ipDialog.isShowing()){
                            ipDialog.dismiss();
                        }
                        showAnimaDialog(LoginActivity.this, "配置检验失败，请重新输入");
                    }
                }, map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            if (ipDialog!=null&&ipDialog.isShowing()){
                ipDialog.dismiss();
            }
            showAnimaDialog(LoginActivity.this, "请开启网络连接，配置过可直接登录");
        }
    }



    //跳转至系统页面设置
    protected void requestPermission() {
        // 6.0以上系统才可以判断权限
        // 进入设置系统应用权限界面
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        startActivity(intent);


    }


    /**
     * 广播的注册，与静态注册一起使用
     */
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
        //输入法内存回收
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        try {
            InputMethodManager.class.getDeclaredMethod("windowDismissed", IBinder.class).invoke(imm,
                    getWindow().getDecorView().getWindowToken());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    //需要有效输入
    public void clearDb(){
        String name = sp.getString("userNum","null");
        if (!name.equals("null")){ //是否有记录
            if (!name.equals(uNum)){//登录名不同
                //清除本地数据
                try {
//                    final List<Schedule> sch = db.selector(Schedule.class).findAll();
//                    final List<Shop> shops = db.selector(Shop.class).findAll();
//                    final List<CommonMapBean> commonMapBeen = db.selector(CommonMapBean.class).findAll();
                    final List<Employee> emp = db.selector(Employee.class).findAll();
//                    final List<RMain> rmian = db.selector(RMain.class).findAll();
//                    final List<tempLostRR> rr = db.selector(tempLostRR.class).findAll();
//                    final List<departBean> depart = db.selector(departBean.class).findAll();
//                    final List<SignUpInfo> signUpInfos = db.selector(SignUpInfo.class).findAll();
//                    final List<sType> sTypes = db.selector(sType.class).findAll();

                    //有数据则提示
                    if (emp!=null&&emp.size()>0){
                            if (netWorkStateReceiver.whetherConnectNetWork==1){
                                MaterialDialogUtils.showMaterialDialog(this, "切换用户将清空所有未提交的评估信息，是否继续登录", "确定", "取消", true, true, new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        try {
                                          db.dropDb();
                                        } catch (DbException e) {
                                            e.printStackTrace();
                                        }
                                        longinRequest();
                                    }
                                }, new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    }
                                });
                            }else{
                                //当前处于离线状态，只能以之前账号登录
                                BaseActivity.showAnimaDialog(LoginActivity.this,"当前处于离线状态，只能以之前账号登录");
                            }
                    }else{//没有存储
                        longinRequest();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }else{//登录名相同
                longinRequest();
            }
        }else{//无登录存储记录
            longinRequest();
        }
    }

    public void getAllPerssion(){
        //判断是否第一次登陆
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionsNeeded = new ArrayList<>();
            final List<String> permissionsList = new ArrayList<>();
            //sdk读写权限
            if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
                permissionsNeeded.add("Read SDcard");
            if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                permissionsNeeded.add("Write SDcard");
            //相机权限
            if (!addPermission(permissionsList, Manifest.permission.CAMERA))
                permissionsNeeded.add("CAMERA");
            //定位权限
            if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
                permissionsNeeded.add("Location");
                //  录音权限
                if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
                    permissionsNeeded.add("RECORD AUDIO");
                if(!addPermission(permissionsList,Manifest.permission.READ_PHONE_STATE))
                    permissionsNeeded.add("READ PHONE");
                if (permissionsList.size() > 0) {
              //      if (permissionsNeeded.size() > 0) {
                        // Need Rationale
//                        String message = "需要以下权限授权，请点击OK按钮";
////                        for (int i = 1; i < permissionsNeeded.size(); i++)
////                            message = message + ", " + permissionsNeeded.get(i);i
//                        showMessageOKCancel(message,
//                                new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
//                                                REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
//                                    }
//                                });
//                        return;
//                    }
                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                }
            }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            if (!shouldShowRequestPermissionRationale(permission)){
                return false;
            }
        }
        return true;
    }
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(LoginActivity.this)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //光标在text后面
        userNum.setSelection(userNum.length());
        if(userNum.length()==0&&userPass.length()>0){
            userPass.setText("");
        }
    }

    private void setdefultDialog(ProgressDialog dialog){
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_SPACE;
            }
        });
        dialog.setCancelable(false);
    }
    //登录清除门店，日程数据,防止日程或门店删除本地有数据
    public void clearShopAndSchedule() throws DbException {
        final List<Schedule> sch = db.selector(Schedule.class).findAll();
        if (sch!=null&&sch.size()>0){
            db.delete(Schedule.class);
        }
        final List<Shop> shops = db.selector(Shop.class).findAll();
        if (shops!=null&&shops.size()>0){
            db.delete(Shop.class);
        }
    }

}
